/**
 * Copyright (C) 2013-2015
 *
 * @file   S_2_Lock_doEvent.c
 *
 * @remark
 *
 */

#include <time.h>
#include "S_2_Lock_doEvent.h"
#include "miio_user_api.h"
#include "iid.h"
//#include "lock_operation.h"
//#include "lock_history.h"
#include "data_uart.h"

#define UART_LOG_ENABLE     1

extern int gatt_send_event_occurred_internal(uint8_t siid, uint16_t eiid, arguments_t *newArgs);

void E_2_1007_Exception_Occurred_doEvent(uint8_t abnormal)
{
    if (get_mi_reg_stat() == 0){
        MI_LOG_ERROR("device unregistered!\n");
        return;
    }
    
    // 初始化参数列表
    arguments_t * newArgs = arguments_new();
    if (newArgs == NULL)
    {
        MI_LOG_ERROR("arguments_new failed!\n");
        return;
    }

    // 参数个数
    newArgs->size = 2;
    newArgs->arguments[0].piid = 1;
    newArgs->arguments[0].value = property_value_new_uchar(abnormal);
    newArgs->arguments[1].piid = 2;
    //xiaomi_lock.s_utc = time(NULL);//mible_systime_utc_get();
    newArgs->arguments[1].value = property_value_new_ulong(time(NULL));

    //发送消息到手机
    if(get_mi_authorization()){
        gatt_send_event_occurred_internal(2, 1007, newArgs);
    }
    //event is Urgent, 发送消息到服务器
    miio_ble_event_occurred(2, 1007, newArgs, 1);

#if UART_LOG_ENABLE
//    lock_history_store(0, 0, MIBLE_LOCK_HISTORY_TYPE_ABNORMAL, abnormal);
    data_uart_debug("Exception_Occurred: abnormal %d, utc %d\r\n", abnormal, time(NULL));
#endif
}

void E_2_1020_Lock_Event_doEvent(uint8_t position, uint8_t method, uint8_t action, uint16_t op_id)
{
    if (get_mi_reg_stat() == 0){
        MI_LOG_ERROR("device unregistered!\n");
        return;
    }

    // 初始化参数列表
    arguments_t * newArgs = arguments_new();
    if (newArgs == NULL)
    {
        MI_LOG_ERROR("arguments_new failed!\n");
        return;
    }

    // 参数个数
    newArgs->size = 5;
    newArgs->arguments[0].piid = 1;
    newArgs->arguments[0].value = property_value_new_uchar(position);
    newArgs->arguments[1].piid = 2;
    newArgs->arguments[1].value = property_value_new_uchar(method);
    newArgs->arguments[2].piid = 3;
    newArgs->arguments[2].value = property_value_new_uchar(action);
    newArgs->arguments[3].piid = 5;
    newArgs->arguments[3].value = property_value_new_ushort(op_id);
    newArgs->arguments[4].piid = 6;
    //xiaomi_lock.s_utc = time(NULL);//mible_systime_utc_get();
    newArgs->arguments[4].value = property_value_new_ulong(time(NULL));

    //发送消息到手机
    if(get_mi_authorization()){
        gatt_send_event_occurred_internal(2, 1020, newArgs);
    }
    //event is Urgent, 发送消息到服务器
    miio_ble_event_occurred(2, 1020, newArgs, 1);
    
#if UART_LOG_ENABLE
//    lock_history_store(position, method, op_id, action);
    data_uart_debug("Lock_Event: pos %d, method %d, act %d, id %d, utc %d\r\n", 
            position, method, action, op_id, time(NULL));
#endif
}
